package part4;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;


/**
 * MainWriteReadCompare
 *  - Try to write two objects to a file and read them back in;
 *    then check if the two are the same
 *  - This program will crash - find out why and fix it!
 * @author tony
 *
 */
public class MainWriteReadCompare {
	public static void main(String[] args) {
		final String OUTPUTFILENAME = "output.obj";
		NewData1 d1 = new NewData1( 10, "Hello" );
		NewData2 d2 = new NewData2( 11, "Hello Hello" );
		System.out.println( "In this program, first we will write an object to the file " + OUTPUTFILENAME );
		try {
			FileOutputStream fo = new FileOutputStream( OUTPUTFILENAME );
			ObjectOutputStream oos = new ObjectOutputStream(fo);
			oos.writeObject(d1);
			oos.writeObject(d2);
			oos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("OK, done - refresh your project to see the file.");
		
		
		final String INPUTFILENAME = OUTPUTFILENAME;
		NewData1 rd1 = null;
		NewData2 rd2 = null;
		System.out.println( "Next, we will read an object from the file " + INPUTFILENAME );
		try {
			FileInputStream fi = new FileInputStream( INPUTFILENAME );
			ObjectInputStream ois = new ObjectInputStream( fi );
			rd1 = (NewData1) ois.readObject();
			rd2 = (NewData2) ois.readObject();
			ois.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		System.out.println( "   OK, done reading. We read in " + d2 );

		if (d1.equals(rd1))
			System.out.println("The input is the same as the output");
		else
			System.out.println("The input is not the same as the output");
		if (d2.equals(rd2))
			System.out.println("The input is the same as the output");
		else
			System.out.println("The input is not the same as the output");
	}
}
